#include "hal.h"
#include "mongoose_glue.h"

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <pthread.h>

#include "led_drv.h"

int fd;

extern void my_set_led1(struct led1 *data);
extern void my_set_led2(struct led2 *data);

void *key_listen_task(void *args)
{
    (void)args;
    int key_num;
    while (1)
    { // 阻塞式等待
        read(fd, &key_num, 4);
        mg_log("监测到: 按键[%d]被按下!\n", key_num);
        if (key_num == 1)
        {
            // key1 led1亮
            struct led1 data = {.value = 1};
            my_set_led1(&data);
        }
        else if (key_num == 2)
        {
            // key2 led2亮
            struct led2 data = {.value = 1};
            my_set_led2(&data);
        }
        else if (key_num == 3)
        { // key3 led1和led2都灭
            struct led1 data1 = {.value = 0};
            my_set_led1(&data1);
            struct led2 data2 = {.value = 0};
            my_set_led2(&data2);
        }
        else
        {
            printf("按键[%d]无效!!!!!!!!!!!!!!!!!!!!!!!\n", key_num);
        }
    }
    return NULL;
}

void key_init()
{
    //
    fd = open("/dev/key_drv", O_RDWR);
    //
    pthread_t tid;
    pthread_create(&tid, NULL, (void *)key_listen_task, NULL);
    pthread_detach(tid); // 线程分离，避免资源泄漏
}